package com.neuedu.javase.thread;

// 仓库(有界缓冲区)
class Storage{
	private int count = 0;
	public synchronized void set(){
		if(count>=5){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		count++;
		System.out.println("生产了一个，仓库中有：" + count);
		this.notify();
	}
	public synchronized void get(){
		if(count<=0){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		count--;
		System.out.println("消费了一个，仓库中有：" + count);
		this.notify();
	}
}
// 生产者
class Producer extends Thread{
	private Storage storage;
	public Producer(Storage storage){
		this.storage = storage;
	}
	public void run(){
		for(int i=0;i<50;i++){
			this.storage.set();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
	}
}
// 消费者
class Customer extends Thread{
	private Storage storage;
	public Customer(Storage storage){
		this.storage = storage;
	}
	public void run(){
		for(int i=0;i<50;i++){
			this.storage.get();
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
		}
	}
}
public class WatiNotifyThread {
	public static void main(String[] args) {
		Storage storage = new Storage();
		Producer producer = new Producer(storage);
		Customer customer = new Customer(storage);
		
		customer.start();
		producer.start();
	}
}